package com.zyj.test.month1.day7;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Yijia Zhang
 * @create 2024-04-28 23:37
 */
public class code0014 {
    public String longestCommonPrefixV2(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }
        Arrays.sort(strs, Comparator.comparingInt(String::length));
        String first = strs[0];
        for (int i = first.length(); i > 0; i--) {
            String s = first.substring(0, i);
            boolean allin = false;
            for (String str : strs) {
                if (!str.startsWith(s)) {
                    allin = true;
                    break;
                }
            }
            if (!allin) {
                return s;
            }
        }
        return "";
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }

        int minLen = Integer.MAX_VALUE;
        for (String str : strs) {
            minLen = Math.min(minLen, str.length());
        }
        String first = strs[0];
        for (int i = minLen; i > 0; i--) {
            String s = first.substring(0, i);
            boolean allin = false;
            for (String str : strs) {
                if (!str.startsWith(s)) {
                    allin = true;
                    break;
                }
            }
            if (!allin) {
                return s;
            }
        }
        return "";
    }
}
